<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="keywords" content="anhoder的进阶日志">
<meta name="description" content="一川烟草，满城风絮。">
<meta name="theme-color" content="#000">
<title>读《细说PHP》 | anhoder的进阶日志</title>
<link rel="shortcut icon" href="/favicon.ico?v=1640406618472">
<link rel="stylesheet" href="/media/css/pisces.css">
<link rel="stylesheet" href="/media/fonts/font-awesome.css">
<link
  href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Rosario:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext"
  rel="stylesheet" type="text/css">

<link href="/media/hljs/styles/androidstudio.css"
  rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/themes/green/pace-theme-minimal.css" rel="stylesheet" />

<link rel="stylesheet" href="/styles/main.css">

<script src="/media/hljs/highlight.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.ui.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"
  integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">


<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"
  integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"
  integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous"
  onload="renderMathInElement(document.body);"></script>



<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-161423102-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag() { dataLayer.push(arguments); }
  gtag('js', new Date());

  gtag('config', 'UA-161423102-1');
</script>


<script>
  var _hmt = _hmt || [];
  (function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?bdf14d3cd277bc2dfa9f84d19b36a686";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>


  <meta name="description" content="读《细说PHP》" />
  <meta name="keywords" content="PHP" />
</head>

<body>
  <div class="head-top-line"></div>
  <div class="header-box">
    
<div class="pisces">
  <header class="header  ">
    <div class="blog-header box-shadow-wrapper bg-color " id="header">
      <div class="nav-toggle" id="nav_toggle">
        <div class="toggle-box">
          <div class="line line-top"></div>
          <div class="line line-center"></div>
          <div class="line line-bottom"></div>
        </div>
      </div>
      <div class="site-meta">       
        <div class="site-title">
          
            <a href="/" class="brand">
              <span>anhoder的进阶日志</span>
            </a>  
          
        </div>
        
          <p class="subtitle">太阳不热，糖也正适合。</p>
        
      </div>
      <nav class="site-nav" id="site_nav">
        <ul id="nav_ul">
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/" target="_self">
                    <i class="fa fa-home"></i> 首页
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/archives/" target="_self">
                    <i class="fa fa-archive"></i> 归档
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/tags/" target="_self">
                    <i class="fa fa-tags"></i> 标签
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/post/about/" target="_self">
                    <i class="fa fa-user"></i> 关于
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="https://github.com/anhoder/" target="_blank">
                    <i class="fa fa-github"></i> GitHub
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/media/excalidraw/" target="_self">
                    <i class="fa fa-picture-o"></i> 制作手绘图
                  </a>
                
              
            </li>
          
          
          
        </ul>
      </nav>
    </div>
  </header>
</div>

<script type="text/javascript"> 
 
  let showNav = true;

  let navToggle = document.querySelector('#nav_toggle'),
  siteNav = document.querySelector('#site_nav');
  
  function navClick() {
    let sideBar = document.querySelector('.sidebar');
    let navUl = document.querySelector('#nav_ul');
    navToggle.classList.toggle('nav-toggle-active');
    siteNav.classList.toggle('nav-menu-active');
    if (siteNav.classList.contains('nav-menu-active')) {
      siteNav.style = "height: " + (navUl.children.length * 42) +"px !important";
    } else {
      siteNav.style = "";
    }
  }

  navToggle.addEventListener('click',navClick);  
</script>
  </div>
  <div class="main-continer">
    
    <div
      class="section-layout pisces ">
      <div class="section-layout-wrapper">
        

<div class="sidebar">
  
    <div class="sidebar-box box-shadow-wrapper bg-color right-motion" id="sidebar">
      
        <div class="post-list-sidebar">
          <div class="sidebar-title">
            <span id="tocSideBar" class="sidebar-title-item sidebar-title-active language" data-lan="index">文章目录</span>
            <span id="metaSideBar" class="sidebar-title-item language" data-lan="preview">站点概览</span>
          </div>
        </div>
      
      <div class="sidebar-body pisces" id="sidebar_body">
        
          
            <div class="post-side-meta" id="post_side_meta">
              
<div class="sidebar-wrapper box-shadow-wrapper bg-color">
  <div class="sidebar-item">
    <img class="site-author-image right-motion" src="/images/avatar.png"/>
    <p class="site-author-name">anhoder</p>
    
  </div>
  <div class="sidebar-item side-item-stat right-motion">
    <div class="sidebar-item-box">
      <a href="/archives/">
        
        <span class="site-item-stat-count">94</span>
        <span class="site-item-stat-name language" data-lan="article">文章</span>
      </a>
    </div>
    <div class="sidebar-item-box">
      <a href="">
        <span class="site-item-stat-count">27</span>
        <span class="site-item-stat-name language" data-lan="category">分类</span>
      </a>
    </div>
    <div class="sidebar-item-box">
      <a href="/tags/">
        <span class="site-item-stat-count">27</span>
        <span class="site-item-stat-name language" data-lan="tag">标签</span>
      </a>
    </div>
  </div>
  
    
  
  
    <div class="sidebar-item sidebar-item-social">
      <div class="social-item">
        
          
            <a href="https://github.com/anhoder">
              <i class="fa fa-github-alt" title="GitHub"></i>
            </a>
          
            <a href="https://twitter.com/Alan_Albert_">
              <i class="fa fa-twitter" title="Twitter"></i>
            </a>
          
            <a href="https://weibo.com/u/5794659803">
              <i class="fa fa-weibo" title="Weibo"></i>
            </a>
          
            <a href="mailto:anhoder@88.com">
              <i class="fa fa-envelope" title="Email"></i>
            </a>
          
            <a href="https://stackoverflow.com/users/9723854/alan">
              <i class="fa fa-stack-overflow" title="StackOverflow"></i>
            </a>
          
        
        
          
            <a class="social-img" href="#">
              <img src="/media/images/custom-array-imgSocials-1617614181832-socialImg.png" />
              <i class="fa fa-weixin" title="微信公众号" ></i>
            </a>
          
        
      </div>
    </div>
  

  



</div>
            </div>
            <div class="post-toc sidebar-body-active" id="post_toc" style="opacity: 1;">
              <div class="toc-box right-motion">
  <div class="toc-wrapper  auto"
    id="toc_wrapper">
    <ul class="markdownIt-TOC">
<li>
<ul>
<li><a href="#%E4%B8%80-php%E7%9A%84%E9%94%99%E8%AF%AFerror%E4%B8%8E%E5%BC%82%E5%B8%B8exception">一、PHP的错误ERROR与异常EXCEPTION</a>
<ul>
<li><a href="#%E9%94%99%E8%AF%AFerror">错误ERROR</a></li>
<li><a href="#%E5%BC%82%E5%B8%B8exception">异常EXCEPTION</a></li>
<li><a href="#%E6%8D%95%E8%8E%B7%E9%94%99%E8%AF%AF%E5%92%8C%E5%BC%82%E5%B8%B8">捕获错误和异常</a>
<ul>
<li><a href="#error_reporting%E5%87%BD%E6%95%B0">error_reporting函数</a></li>
<li><a href="#set_error_handler%E5%87%BD%E6%95%B0">set_error_handler函数</a></li>
<li><a href="#register_shutdown_function%E5%87%BD%E6%95%B0">register_shutdown_function函数</a></li>
<li><a href="#error_get_last%E5%87%BD%E6%95%B0">error_get_last函数</a></li>
<li><a href="#set_exception_handler%E5%87%BD%E6%95%B0">set_exception_handler函数</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#%E4%BA%8C-%E6%97%A5%E6%9C%9F%E4%B8%8E%E6%97%B6%E9%97%B4">二、日期与时间</a></li>
<li><a href="#%E4%B8%89-%E6%96%87%E4%BB%B6%E4%B8%8E%E7%9B%AE%E5%BD%95">三、文件与目录</a>
<ul>
<li><a href="#%E7%B1%BB%E5%9E%8B">类型</a></li>
<li><a href="#%E6%96%87%E4%BB%B6">文件</a></li>
<li><a href="#%E7%9B%AE%E5%BD%95">目录</a></li>
<li><a href="#%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6">上传文件</a></li>
<li><a href="#%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6">下载文件</a></li>
</ul>
</li>
<li><a href="#%E5%9B%BE%E5%83%8F%E7%BB%98%E5%88%B6">图像绘制</a>
<ul>
<li><a href="#%E5%88%9B%E5%BB%BA%E7%94%BB%E5%B8%83">创建画布</a></li>
<li><a href="#%E8%AE%BE%E7%BD%AE%E9%A2%9C%E8%89%B2">设置颜色</a></li>
<li><a href="#%E7%BB%98%E5%88%B6">绘制</a></li>
<li><a href="#%E7%94%9F%E6%88%90%E5%9B%BE%E5%83%8F">生成图像</a></li>
<li><a href="#%E9%94%80%E6%AF%81%E5%9B%BE%E5%83%8F">销毁图像</a></li>
</ul>
</li>
<li><a href="#%E5%9B%BE%E5%83%8F%E5%A4%84%E7%90%86">图像处理</a></li>
<li><a href="#pdo">PDO</a>
<ul>
<li><a href="#pdo%E9%A9%B1%E5%8A%A8">PDO驱动</a></li>
<li><a href="#pdo%E7%B1%BB%E7%9A%84%E6%96%B9%E6%B3%95">PDO类的方法</a>
<ul>
<li><a href="#%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95">构造方法</a></li>
<li><a href="#attribute">Attribute</a></li>
<li><a href="#%E9%94%99%E8%AF%AF">错误</a></li>
<li><a href="#sql">SQL</a></li>
</ul>
</li>
<li><a href="#%E9%A2%84%E5%A4%84%E7%90%86%E8%AF%AD%E5%8F%A5%E5%92%8Cpdostatement%E7%B1%BB">预处理语句和PDOStatement类</a></li>
</ul>
</li>
<li><a href="#memcached">MemCached</a>
<ul>
<li><a href="#memcached%E5%91%BD%E4%BB%A4">MemCached命令</a></li>
<li><a href="#%E5%9C%A8php%E4%B8%AD%E4%BD%BF%E7%94%A8memcached">在PHP中使用MemCached</a></li>
</ul>
</li>
<li><a href="#%E6%A1%86%E6%9E%B6">框架</a></li>
<li><a href="#php%E5%AE%89%E5%85%A8%E5%92%8C%E4%BC%98%E5%8C%96">PHP安全和优化</a></li>
</ul>
</li>
</ul>

  </div>
</div>

<script>

  let lastTop = 0, lList = [], hList = [], postBody, lastIndex = -1;
  let active = 'active-show', activeClass = 'active-current';
  let tocWrapper = document.querySelector('#toc_wrapper');
  let tocContent = tocWrapper.children[0];
  let autoNumber = tocWrapper && tocWrapper.classList.contains('auto-number');

  function addTocNumber(elem, deep) {
    if (!elem) {
      return;
    }
    let prop = elem.__proto__;

    if (prop === HTMLUListElement.prototype) {
      for (let i = 0; i < elem.children.length; i++) {
        addTocNumber(elem.children[i], deep + (i + 1) + '.');
      }
    } else if (prop === HTMLLIElement.prototype) {
      // 保存li元素
      if (elem.children[0] && elem.children[0].__proto__ === HTMLAnchorElement.prototype) {
        lList.push(elem);
      }
      for (let i = 0; i < elem.children.length; i++) {
        let cur = elem.children[i];
        if (cur.__proto__ === HTMLAnchorElement.prototype) {
          if (autoNumber) {
            cur.text = deep + ' ' + cur.text;
          }
        } else if (cur.__proto__ === HTMLUListElement.prototype) {
          addTocNumber(cur, deep);
        }
      }
    }
  }

  function removeParentActiveClass() {
    let parents = tocContent.querySelectorAll('.' + active)
    parents.forEach(function (elem) {
      elem.classList.remove(active);
    });
  }

  function addActiveClass(index) {
    if (index >= 0 && index < hList.length) {
      lList[index].classList.add(activeClass);
    }
  }

  function removeActiveClass(index) {
    if (index >= 0 && index < hList.length) {
      lList[index].classList.remove(activeClass);
    }
  }

  function addActiveLiElemment(elem, parent) {
    if (!elem || elem === parent) {
      return;
    } else {
      if (elem.__proto__ === HTMLLIElement.prototype) {
        elem.classList.add(active);
      }
      addActiveLiElemment(elem.parentElement, parent);
    }
  }

  function showToc() {
    if (tocWrapper) {
      postBody = document.querySelector('#post_body');
      for (let i = 0; i < postBody.children.length; i++) {
        if (postBody.children[i].__proto__ === HTMLHeadingElement.prototype) {
          hList.push(postBody.children[i]);
        }
      }
      if (tocWrapper.classList.contains('compress')) {
        tocContent.classList.add('closed');
      } else if (tocWrapper.classList.contains('no_compress')) {
        tocContent.classList.add('expanded');
      } else {
        if (hList.length > 10) {
          active = 'active-hidden'
          tocContent.classList.add('closed');
        } else {
          tocContent.classList.add('expanded');
        }
      }
    }
  }

  (function () {
    // 处理不是从#一级标题开始目录
    if (tocContent.children.length === 1 && tocContent.children[0].__proto__ === HTMLLIElement.prototype) {
      let con = tocContent.children[0].children[0];
      tocContent.innerHTML = con.innerHTML;
    }
    let markdownItTOC = document.querySelector('.markdownIt-TOC');
    let innerHeight = window.innerHeight;
    markdownItTOC.style = `max-height: ${innerHeight - 80 > 0 ? innerHeight - 80 : innerHeight}px`
    addTocNumber(tocContent, '');
  })();

  document.addEventListener('scroll', function (e) {
    if (lList.length <= 0) {
      return;
    }
    let scrollTop = document.scrollingElement.scrollTop + 10;
    let dir;

    if (lastTop - scrollTop > 0) {
      dir = 'up';
    } else {
      dir = 'down';
    }

    lastTop = scrollTop;
    if (scrollTop <= 0) {
      if (lastIndex >= 0 && lastIndex < hList.length) {
        lList[lastIndex].classList.remove(activeClass);
      }
      return;
    }

    let current = 0, hasFind = false;
    for (let i = 0; i < hList.length; i++) {
      if (hList[i].offsetTop > scrollTop) {
        current = i;
        hasFind = true;
        break;
      }
    }
    if (!hasFind && scrollTop > lList[lList.length - 1].offsetTop) {
      current = hList.length - 1;
    } else {
      current--;
    }
    if (dir === 'down') {
      if (current > lastIndex) {
        addActiveClass(current);
        removeActiveClass(lastIndex)
        lastIndex = current;
        removeParentActiveClass();
        lList[current] && addActiveLiElemment(lList[current].parentElement, tocContent);
      }
    } else {
      if (current < lastIndex) {
        addActiveClass(current);
        removeActiveClass(lastIndex);
        lastIndex = current;
        removeParentActiveClass();
        lList[current] && addActiveLiElemment(lList[current].parentElement, tocContent);
      }
    }
  });


  window.addEventListener('load', function () {
    showToc();
    document.querySelector('#sidebar').style = 'display: block;';
    tocWrapper.classList.add('toc-active');
    setTimeout(function () {
      if ("createEvent" in document) {
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("scroll", false, true);
        document.dispatchEvent(evt);
      }
      else {
        document.fireEvent("scroll");
      }
    }, 500)
  })

</script>
            </div>
          
        
      </div>
    </div>
  
</div>
<script>
  const SIDEBAR_TITLE_ACTIVE = 'sidebar-title-active';
  const SIDEBAR_BODY_ACTIVE = 'sidebar-body-active';
  const SLIDE_UP_IN = 'slide-up-in';

  let sidebar = document.querySelector('#sidebar'),
  tocSideBar = document.querySelector('#tocSideBar'),
  metaSideBar = document.querySelector('#metaSideBar'),
  postToc = document.querySelector('#post_toc'),
  postSiteMeta = document.querySelector('#post_side_meta'),
  sidebarTitle = document.querySelector('.sidebar-title'),
  sidebarBody = document.querySelector('#sidebar_body');

  tocSideBar && tocSideBar.addEventListener('click', (e) => {
    toggleSidebar(e);
  });

  metaSideBar && metaSideBar.addEventListener('click', (e) => {
    toggleSidebar(e);
  });

  function toggleSidebar(e) {
    let currentTitle = document.querySelector("."+SIDEBAR_TITLE_ACTIVE);
    if (currentTitle == e.srcElement) {
      return ;
    }
    let current, showElement, hideElement;
    if (e.srcElement == metaSideBar) {
      showElement = postSiteMeta;
      hideElement = postToc;
    } else if (e.srcElement == tocSideBar){
      showElement = postToc;
      hideElement = postSiteMeta;
    }
    currentTitle.classList.remove(SIDEBAR_TITLE_ACTIVE);
    e.srcElement.classList.add(SIDEBAR_TITLE_ACTIVE);

    window.Velocity(hideElement, 'stop');
    window.Velocity(hideElement, 'transition.slideUpOut', {
      display: 'none',
      duration: 200,
      complete: function () {
        window.Velocity(showElement, 'transition.slideDownIn', {
          duration: 200
        });
      }
    })
    hideElement.classList.remove(SIDEBAR_BODY_ACTIVE);
    showElement.classList.add(SIDEBAR_BODY_ACTIVE);
  }

  postToc && postToc.addEventListener('transitionend', function() {
    this.classList.remove(SLIDE_UP_IN);
  });

  if (sidebarBody) {
    if (sidebarBody.classList.contains('pisces') || sidebarBody.classList.contains('gemini')) {
      let hasFix = false;
      let scrollEl = document.querySelector('.main-continer');
      let limitTop = document.querySelector('#nav_ul').children.length * 42 + 162;
      window.addEventListener('scroll', function(e) {
        if (document.scrollingElement.scrollTop >= limitTop) {
          if (!hasFix) {
            sidebar.classList.add('sidebar-fixed');
            hasFix = true;
          }
        } else {
          if (hasFix) {
            sidebar.classList.remove('sidebar-fixed');
            hasFix = false;
          }
        }
      });
    }
  }
  
</script>
        <div class="section-box box-shadow-wrapper">
          <div class="section bg-color post post-page">
            <section class="post-header">
  <h1 class="post-title">
    <a class="post-title-link" href="/post/wj0p65Bqw/">
      读《细说PHP》
    </a>
  </h1>
  <div class="post-meta">
    
    <span class="meta-item pc-show">
      <i class="fa fa-calendar-o"></i>
      <span class="language" data-lan="publish">发布于</span>
      <span class="publish-time" data-t="2018-12-21 19:25:06">2018-12-21</span>
      <span class="post-meta-divider pc-show">|</span>
    </span>
    
    <span class="meta-item">
      <i class="fa fa-folder-o"></i>
      <span class="pc-show language" data-lan="category-in">分类于</span>
      
      
      <a href="/tag/wKIDH6M-M/">
        <span>PHP</span>
      </a>
      
      
    </span>
    <span class="post-meta-divider">|</span>
    
    <span class="meta-item">
      <i class="fa fa-clock-o"></i>
      <span>18<span class="language" data-lan="minute">分钟</span></span>
    </span>
    <span class="meta-item">
      <span class="post-meta-divider">|</span>
      <i class="fa fa-file-word-o"></i>
      <span>4375<span class="pc-show language" data-lan="words">字数</span></span>
    </span>
    
  </div>
</section>
            <div class="post-body next-md-body" id="post_body">
              <!-- more -->
<h2 id="一-php的错误error与异常exception">一、PHP的错误ERROR与异常EXCEPTION</h2>
<p><em>注意：在不同的语言中，错误与异常的定义不同。因此以下内容只在PHP中成立。</em></p>
<h3 id="错误error">错误ERROR</h3>
<p>错误：属于PHP脚本自身的问题，可能是由错误的语法、服务器环境等导致，使得编译器无法通过检查，甚至无法运行的情况。</p>
<p><strong>错误不能被try/catch捕获</strong></p>
<p>错误的级别：</p>
<ul>
<li>
<p>Fatal Error  致命错误，脚本终止运行</p>
<ul>
<li>E_ERRO: 致命的运行时错误，阻止脚本的执行</li>
<li>E_CORE_ERROR: PHP初始化启动过程发生的错误，由PHP引擎核心产生</li>
<li>E_COMPILE_ERROR: 致命编译时错误，由Zend脚本引擎产生</li>
<li>E_USER_ERROR: 用户产生的错误信息，在代码中使用函数trigger_error()产生（错误类型设置为E_USER_ERROR）</li>
</ul>
</li>
<li>
<p>Parse Error  编译时解析错误，语法错误，脚本终止运行</p>
<ul>
<li>E_PARSE: 编译时语法解析错误，仅有分析器产生</li>
</ul>
</li>
<li>
<p>Warning Error  警告错误，脚本不终止运行</p>
<ul>
<li>E_WARNING: 运行时警告，非致命错误</li>
<li>E_CORE_WARNING: PHP初始化启动过程中发生的警告，非致命错误，由PHP引擎核心产生</li>
<li>E_COMPILE_WARNING: 编译时警告，非致命错误，由Zend脚本产生</li>
<li>E_USER_WARNING: 用户产生的警告信息，在代码中使用函数trigger_error()产生（错误类型设置为E_USER_WARNING）</li>
</ul>
</li>
<li>
<p>Notice Error  通知错误，脚本不终止运行</p>
<ul>
<li>E_NOTICE: 运行时通知，表示脚本遇到可能会表现为错误的情况，但是在可以正常运行的脚本里面也可能会有类似的通知</li>
<li>E_USER_NOTICE: 用户产生的通知信息，在代码中使用函数trigger_error()产生（错误类型设置为E_USER_NOTICE）</li>
</ul>
<p>另外：</p>
<ul>
<li>E_ALL: 除E_ALL外的所有的错误、警告和注意</li>
<li>E_STRICT: 关于PHP版本移植的兼容性和互操作性建议</li>
</ul>
</li>
</ul>
<h3 id="异常exception">异常EXCEPTION</h3>
<p>异常：在程序运行期间出现的不符合预期的情况，允许发生但不正常的情况。属于业务逻辑的错误，而不是语法或编译的错误。</p>
<h3 id="捕获错误和异常">捕获错误和异常</h3>
<p>在PHP中，用于捕获异常和错误的几个重要函数：<strong>error_reporting</strong>、<strong>set_error_handler</strong>、<strong>register_shutdown_function</strong>、<strong>error_get_last</strong>、<strong>set_exception_handler</strong>。</p>
<h4 id="error_reporting函数">error_reporting函数</h4>
<p>设置报告哪些错误</p>
<pre><code class="language-php">int error_reporting([int $err_type])

/**
 * int $err_type 可选参数，需要设置错误等级
 * 返回值：int 返回旧的错误级别
 */
</code></pre>
<p>用例：</p>
<pre><code class="language-php">error_report(E_ALL | E_STRICT);
</code></pre>
<h4 id="set_error_handler函数">set_error_handler函数</h4>
<p>捕获错误，并执行用户自定义的错误处理函数。</p>
<pre><code class="language-php">mixed set_error_handler(callable $error_handler 
    [, int $error_types = E_ALL | E_STRICT])
/**
 * callable $error_handler
 *     回调函数，需要声明四个参数：错误类型、错误信息、错误所在文件、错误所在行。
 *     第五个参数可选，指向错误发生时活动符号表的array，但在PHP 7.2.0被废）
 *     
 * int $error_types
 *     可选，规定在哪个错误报告级别显示用户定义的错误
 */
</code></pre>
<p>注意事项：</p>
<blockquote>
<ol>
<li>如果存在该方法，相应的error_reporting()就不能再使用，所有错误都会交给自定义函数处理；</li>
<li>此函数只能捕获系统产生的一些Warning、Notice级别的错误，不能捕获：E_ERROR、E_PARSE、E_CORE_ERROR、E_CORE_WARNING、E_COMPILE_WARNING以及set_error_handler()函数所在文件中产生的E_STRICT。</li>
</ol>
</blockquote>
<p>用例：</p>
<pre><code class="language-php">&lt;?php
    set_error_handler('error_handler');
    function error_handler($err_type, $err_msg, $err_file, $err_line)
    {
        var_dump($err_type);
        var_dump($err_msg);
        var_dump($err_file);
        var_dump($err_line);
    }
    
    // 或者
    
    set_error_handler(array('class_name', 'function_name'));
</code></pre>
<h4 id="register_shutdown_function函数">register_shutdown_function函数</h4>
<p>该函数时PHP脚本执行结束前最后一个调用的函数。通过这个函数就可以在脚本结束前判断是否产生错误。这是需要使用到<strong>error_get_last</strong>函数，获取本次执行产生的所有错误。<strong>register_shutdown_function可以配合set_error_handler捕获所有错误</strong></p>
<pre><code class="language-php">void register_shutdown_function(callable $callback
    [, mixed $parameter
    [, mixed $...]])
/**
 * callable $callback 回调函数
 * mixed $parameter 传递给回调的参数
 * ... 更多回调
 */
</code></pre>
<p>注意事项：</p>
<blockquote>
<ol>
<li>该函数可以捕获的错误：Fatal Error、Parse Error等</li>
<li>register_shutdown_function所在的文件发生语法错误，不能触发回调函数（用例之后会说到）</li>
</ol>
</blockquote>
<p>用例：</p>
<pre><code class="language-php">&lt;?php
    register_shutdown_function('shutdown_handler');
    function shutdown_handler()
    {
        if ($err = error_get_last()) {
            var_dump($err);
        }
    }
</code></pre>
<p>但是，如果执行下列测试文件，是不能触发调用回调函数：</p>
<pre><code class="language-php">&lt;?php
    register_shutdown_function('shutdown_handler');
    function shutdown_handler()
    {
        if ($err = error_get_last()) {
            var_dump($err);
        }
    }
    echo 1++;
</code></pre>
<p>为什么不能触发呢？这是因为：</p>
<blockquote>
<p>如果register_shutdown_function所在文件发生语法错误，该脚本不能通过PHP的语法分析，register_shutdown_function函数就不会被执行，也就没有注册回调函数。</p>
<p>因此，我们需要保证register_shutdown_function所在文件没有语法错误。</p>
</blockquote>
<p>将上述代码修改为：</p>
<pre><code class="language-php">&lt;?php
    register_shutdown_function('shutdown_handler');
    function shutdown_handler()
    {
        if ($err = error_get_last()) {
            var_dump($err);
        }
    }
    require 'a.php';
    
// a.php文件
&lt;?php
    echo 1++;
</code></pre>
<p>修改之后，因为register_shutdown_function所在文件没有语法错误，通过了PHP的语法分析，所以register_shutdown_function函数得以正常运行，便能注册回调函数了。</p>
<p><strong>因此，最好将register_shutdown_function单独放在一个的文件中，并保证该文件没有语法错误。</strong></p>
<h4 id="error_get_last函数">error_get_last函数</h4>
<p>该函数用于获取本次执行中产生的错误信息。</p>
<pre><code class="language-php">array error_get_last()
/**
 * 返回值：array 
 * type =&gt;　错误类型
 * message =&gt; 错误信息
 * file =&gt; 发生错误的文件
 * line =&gt; 发生错误的行号
 */
</code></pre>
<h4 id="set_exception_handler函数">set_exception_handler函数</h4>
<p>设置异常处理函数，如果异常没被捕获就会进到该方法中，并且在回调函数调用后异常会中止。</p>
<pre><code class="language-php">callable set_exception_handler(callable $exception_handler)

/**
 * callable $exception_handler 回调函数，需要接受一个参数：捕获的异常对象
 * 返回值： callable 返回定义的回调函数的名称
 */
</code></pre>
<p><strong>需要注意的是：set_error_handler、register_shutdown_function、set_exception_handler三个函数捕获错误的范围并不是相互独立，可能存在一定的交集，但错误只会被捕获一次，不会重复被捕获</strong></p>
<h2 id="二-日期与时间">二、日期与时间</h2>
<ul>
<li>mktime: 获取时间戳，参数依次为时、分、秒、月、日、年，皆可选</li>
<li>strtotime: 将自然语言英语转换为时间戳</li>
<li>gettimeofday: 获取某一天中的具体时间</li>
<li>getdate: 获取一个由时间戳组成的关联数组，可选参数：一个时间戳</li>
<li>date: 以指定格式返回时间字符串，参数：指定格式，可选参数为时间戳</li>
<li>date_default_timezone_set: 设置默认时区，RPC、Asia/Shanghai、Asia/Chongqing、Etc/GMT-8</li>
<li>microtime: 获取当前微秒级时间戳，可选参数：是否以浮点数形式返回</li>
</ul>
<h2 id="三-文件与目录">三、文件与目录</h2>
<h3 id="类型">类型</h3>
<pre><code class="language-php">// 获取文件类型
filetype(string $file) : string | false
</code></pre>
<p>Windows中PHP只能获取到3种文件类型：file、dir、unknown，而在UNIX中，可以获取7种block、char、dir、fifo、file、link、unknown。</p>
<ul>
<li>block：块设备文件，如：硬盘分区、软驱、光驱等</li>
<li>char：字符设备，指I/O传输中以字符为单位进行传输的设备，如键盘、打印机等</li>
<li>dir：目录类型，目录也是文件的一种</li>
<li>fifo：命名管道，常用于将信息从一个进程传递到另一个进程</li>
<li>file：普通文件类型</li>
<li>link：链接，软链接、硬链接</li>
<li>unknown：未知类型</li>
</ul>
<h3 id="文件">文件</h3>
<ul>
<li>is_file、is_dir、is_link...：判断是否给定的文件为某一类型</li>
<li>file_exists：<strong>文件或目录</strong>是否存在</li>
<li>filesize：文件大小</li>
<li>is_readable：是否可读</li>
<li>is_writeable：是否可写</li>
<li>is_executable：是否可执行</li>
<li>filectime：文件创建时间（inode修改时间）</li>
<li>filemtime：文件修改时间</li>
<li>fileatime：文件访问时间</li>
<li>stat：获取文件的大部分属性值</li>
<li>unlink：删除文件</li>
<li>copy：复制文件</li>
<li>rename：重命名</li>
<li>fopen：打开文件，返回文件句柄，r、r+、w、w+、x、x+、a、a+、b、t</li>
<li>fclose：关闭打开的文件</li>
<li>fwrite：往打开的文件中写</li>
<li>fread：读取打开文件的指定长度内容，参数1为文件句柄，参数2为读取的长度</li>
<li>file_get_content：获取文件内容</li>
<li>fgets：从打开的文件中获取一行</li>
<li>fgets：从打开的文件中获取一个字符</li>
<li>readfile：读取一个文件，并输出到输出缓冲区，返回长度</li>
<li>file：把文件按行读到一个数组中</li>
<li>ftell：返回文件指针的当前位置</li>
<li>fseek：移动文件指针到指定位置</li>
<li>rewind：重置文件指针到文件开头</li>
<li>ftruncate：把文件截取到指定长度</li>
<li>flock：文件锁，LOCK_SH共享锁、LOCK_EX排他锁、LOCK_UN释放锁、LOCK_NB附件锁（如果不希望flock在锁定时堵塞，则应该                                                                       加上该锁），锁也可被fclose释放</li>
</ul>
<table>
<thead>
<tr>
<th>模式</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>r</td>
<td>只读方式打开文件，从文件开头开始读</td>
</tr>
<tr>
<td>r+</td>
<td>读写方式打开文件，从文件开头开始读写，逐个覆盖原内容</td>
</tr>
<tr>
<td>w</td>
<td>只写方式打开文件，从文件开头开始写。若文件已存在，删除原文件内容；若不存在，创建</td>
</tr>
<tr>
<td>w+</td>
<td>读写方式打开文件，从文件开头开始读写。若文件已存在，删除原文件内容；若不存在，创建</td>
</tr>
<tr>
<td>x</td>
<td>创建并以写入方式打开，从文件开头开始写。若文件存在，报出E_WARNING级别的错误</td>
</tr>
<tr>
<td>x+</td>
<td>创建并以读写方式打开，从文件开头开始读写。若文件存在，报出E_WARNING级别的错误</td>
</tr>
<tr>
<td>a</td>
<td>写入方式打开，从文件结尾开始写。若文件不存在，创建</td>
</tr>
<tr>
<td>a+</td>
<td>读写方式打开，从文件结尾开始读写。若文件不存在，创建</td>
</tr>
<tr>
<td>b</td>
<td>以二进制模式打开文件</td>
</tr>
<tr>
<td>t</td>
<td>以文本模式打开文件，只在Windows下可用</td>
</tr>
</tbody>
</table>
<h3 id="目录">目录</h3>
<p>在UNIX系统中，必须使用'/'作为文件分隔符，而在Windows中，默认使用''作为分隔符，同时支持使用'/'作为分隔符。</p>
<p>在PHP中可以使用DIRECTORY_SEPARATOR获取当前系统的分隔符（Windows为''，UNIX为'/'）</p>
<ul>
<li>basename：获取文件名部分，第二个参数可以指定扩展名，如果指定了，返回值则不带扩展名</li>
<li>dirname：获取去掉文件名部分后的目录</li>
<li>pathinfo：获取路径的目录部分dirname、带扩展的文件名basename、扩展extension、不带扩展的文件名filename</li>
<li>dir：返回Directory类的实例</li>
<li>opendir：打开目录，返回目录句柄</li>
<li>readdir：读取目录</li>
<li>closedir：关闭目录</li>
<li>rewinddir：倒回目录句柄，将目录指针重置到开始处</li>
<li>scandir：浏览目录内容</li>
<li>glob：检索指定的目录</li>
<li>mkdir：创建目录</li>
<li>rmdir：删除目录</li>
</ul>
<h3 id="上传文件">上传文件</h3>
<p>需要注意的点：</p>
<ul>
<li>form表单设置enctype=&quot;multipart/form-data&quot; method=&quot;data&quot;</li>
<li>PHP使用$_FILES获取上传文件信息</li>
<li>多文件上传，可指定name=&quot;file[]&quot;的形式</li>
</ul>
<p>处理上传文件可以用到的函数：</p>
<blockquote>
<p>is_uploaded_file：判断处理的文件是否是通过HTTP POST上传的。但参数必须是类似$_POST['file']['tmp_name']的变量。</p>
<p>move_uploaded_file：将上传移动到新位置，且该函数会判断文件是否为合法的通过HTTP POST上传的文件。</p>
</blockquote>
<h3 id="下载文件">下载文件</h3>
<p>设置网页头部信息，以保证浏览器是下载文件而不是直接输出：</p>
<pre><code class="language-php">header('Content-Type: image/gif');
header('Content-Disposition: attachment; filename=&quot;test.gif&quot;'); // 说明是附件
header('Content-Length: 3390');

readfile('test.gif');
</code></pre>
<h2 id="图像绘制">图像绘制</h2>
<h3 id="创建画布">创建画布</h3>
<pre><code class="language-php">resource imagecreate($x_size, $y_size)          // 基于调色板
resource imagecreatetruecolor($x_size, $y_size) // 真彩
</code></pre>
<h3 id="设置颜色">设置颜色</h3>
<pre><code class="language-php">int imagecolorallocate(resource $image, int $r, int $g, int $b)
</code></pre>
<h3 id="绘制">绘制</h3>
<p>图形区域填充</p>
<pre><code class="language-php">bool imagefill(resource $image, int $x, int $y, int $color)
</code></pre>
<p>绘制点和线</p>
<pre><code class="language-php">bool imagesetpixel(resource $image, int $x, int $y, int $color)
bool imageline(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
</code></pre>
<p>绘制矩阵</p>
<pre><code class="language-php">// 画一个矩阵
bool imagerectangle(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
// 画一个矩阵并填充
bool imagefilledrectangle(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)
</code></pre>
<p>绘制多边形</p>
<pre><code class="language-php">bool imagepolygon(resource $image, array $point, int $num_points, int $color)
bool imagefilledpolygon(resource $image, array $point, int $num_points, int $color)
</code></pre>
<p>绘制椭圆</p>
<pre><code class="language-php">bool imageellipse(resource $image, int $cx, int $cy, int $w, int $h, int $color)
bool imagefilledellipse(resource $image, int $cx, int $cy, int $w, int $h, int $color)
// ($cx, $cy) 中心坐标
// $w, $h 宽、高
</code></pre>
<p>绘制弧线</p>
<pre><code class="language-php">bool imagearc(int $cx, int $cy, int $w, int $h, int $s, int $e, int $color)
</code></pre>
<p>绘制文字</p>
<pre><code class="language-php">bool imagestring(resource $image, int $font, int $x, int $y, string $s, int $color) // 水平
bool imagestringup(resource $image, int $font, int $x, int $y, string $s, int $color) // 垂直
bool imagechar(resource $image, int $font, int $x, int $y, char $c, int $color)
bool imagecharup(resource $image, int $font, int $x, int $y, char $c, int $color)
// 以ttf字体绘制文本
array imagettftext(resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text)
</code></pre>
<h3 id="生成图像">生成图像</h3>
<pre><code class="language-php">bool imagegif(resource $image [, string $filename])
bool imagejpeg(resource $image [, string $filename [, int $quality]])
bool imagepng(resource $image [, string $filename])
bool imagewbmp(resource $image [, string $filename [, int $foreground]])
</code></pre>
<h3 id="销毁图像">销毁图像</h3>
<pre><code class="language-php">bool imagedestory(resource $img)
</code></pre>
<h2 id="图像处理">图像处理</h2>
<p>以图片为背景创建图像</p>
<pre><code class="language-php">resource imagecreatefromjpeg(string $file)
resource imagecreatefrompng(string $file)
resource imagecreatefromgif(string $file)
</code></pre>
<p>获取图片大小和类型</p>
<pre><code class="language-php">array getimagesize(string $file [, array &amp;$imageinfo])
</code></pre>
<p>图片缩放、剪切</p>
<pre><code class="language-php">bool imagecopyresampled (resource $dst_img, resource $src_img, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h)
// 该函数可以将图像中的一块正方形区域复制到另一个图像中
</code></pre>
<p>添加水印</p>
<pre><code class="language-php">bool imagecopy(resource $des_img, resource $src_img, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h)
// 将源图像的(src_x, src,y)的宽src_w，高src_h的一部分复制到目标图像的(dst_x, dst_y)处
</code></pre>
<p>图片旋转、翻转</p>
<pre><code class="language-php">resource imagerotate(resource $src_img, float $angle, int $bg_color [, int $ignore_transport])
// 图片旋转angle角度，旋转后未覆盖到的部分使用bg_color填充，igno_transport为非零值，则透明色被忽略。
</code></pre>
<h2 id="pdo">PDO</h2>
<h3 id="pdo驱动">PDO驱动</h3>
<table>
<thead>
<tr>
<th>PDO驱动</th>
<th>对应访问的数据库</th>
</tr>
</thead>
<tbody>
<tr>
<td>PDO_BDLIB</td>
<td>FreeTDS/Microsoft SQL Server/Sybase</td>
</tr>
<tr>
<td>PDO_FIREBIRD</td>
<td>Firbird/Interbase 6</td>
</tr>
<tr>
<td>PDO_MYSQL</td>
<td>MySQL 3.x/4.x/5.x</td>
</tr>
<tr>
<td>PDO_OCI</td>
<td>Oracle (OCI=Oracle Call Interface)</td>
</tr>
<tr>
<td>PDO_ODBC</td>
<td>ODBC v3</td>
</tr>
<tr>
<td>PDO_PGSQL</td>
<td>PostgreSQL</td>
</tr>
<tr>
<td>PDO_SQLITE</td>
<td>SQLite 2.x/3.x</td>
</tr>
</tbody>
</table>
<h3 id="pdo类的方法">PDO类的方法</h3>
<h4 id="构造方法">构造方法</h4>
<pre><code class="language-php">__construct(string $dsn [, string $username [, string $pwd [, array $driver_options]]])
// dsn：Data Source Name，数据源名，如：
// mysql:dbname=test;host=127.0.0.1;port=3306;charset=utf8
// DSN也可指定文件为参数（如果该文件中存放着DSN字符串），如：
// uri:file:///user/local/dbconnect
</code></pre>
<h4 id="attribute">Attribute</h4>
<pre><code class="language-php">// 获取或设置一个数据库连接对象的属性
getAttribute() // 参数：属性名
setAttribute() // 参数：属性名，属性值
</code></pre>
<p>PDO的一些属性</p>
<table>
<thead>
<tr>
<th>属性名</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>PDO::ATTR_AUTOCOMMIT</td>
<td>确定PDO是否关闭自动提交功能，设置FALSE值时关闭</td>
</tr>
<tr>
<td>PDO::ATTR_CASE</td>
<td>强制PDO获取的表字段字符大小写转换，或原样使用列信息</td>
</tr>
<tr>
<td>PDO::ATTR_ERRMODE</td>
<td>设置错误处理模式，PDO::ERRMODE_SILENT, PDO::ERRMODE_WARNING, PDO::ERRMODE_EXCEPTION</td>
</tr>
<tr>
<td>PDO::ATTR_PERSISTENT</td>
<td>确定连接是否为持久连接，默认为FALSE</td>
</tr>
<tr>
<td>PDO::ATTR_ORACLE_NULLS</td>
<td>将返回的空字符串转换为SQL的NULL</td>
</tr>
<tr>
<td>PDO::ATTR_PREFETCH</td>
<td>设置应用程序提前获取的数据大小(单位：K)</td>
</tr>
<tr>
<td>PDO::ATTR_TIMEOUT</td>
<td>设置超时之前等待的时间(单位：s)</td>
</tr>
<tr>
<td>PDO::ATTR_SERVER_INFO</td>
<td>包含与数据库特有的服务器信息</td>
</tr>
<tr>
<td>PDO::ATTR_SERVER_VERSION</td>
<td>包含与数据库服务器版本号有关的信息</td>
</tr>
<tr>
<td>PDO::ATTR_CLIENT_VERSION</td>
<td>包含与数据库客户端版本号有关的信息</td>
</tr>
<tr>
<td>PDO::ATTR_CONNECTION_STATUS</td>
<td>包含数据库特有的与连接状态有关的信息</td>
</tr>
</tbody>
</table>
<h4 id="错误">错误</h4>
<pre><code class="language-php">// 获取最后一次数据库操作的错误码
errorCode()
// 获取最后一次数据库操作的错误信息
errorInfo()
</code></pre>
<h4 id="sql">SQL</h4>
<pre><code class="language-php">exec() // 执行一条SQL语句，并返回受影响的行数
query() // 执行一条SQL语句，并返回PDOStatement对象（结果集）
quote() // 为SQL语句中的字符串添加引号
lastInsertId() // 获取插入到表中的最后一条数据的主键值
prepare() // 准备要执行的SQL语句，返回PDOStatement对象
getAvailableDrivers() // 获取有效的PDO驱动器名称
beginTransaction() // 开始事务
commit() //提交事务
rollback() // 回滚事务
</code></pre>
<h3 id="预处理语句和pdostatement类">预处理语句和PDOStatement类</h3>
<p>通过PDO的prepare方法传入一条预处理语句，返回一个PDOStatement查询对象，可以使用该对象传入参数，执行语句。</p>
<table>
<thead>
<tr>
<th>PDOStatement类的成员方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>bindColumn()</td>
<td>将列名绑定到一个PHP变量，这样获取到记录后，会将相应的列值赋给该变量</td>
</tr>
<tr>
<td>bindParam()</td>
<td>将参数绑定到相应的占位符</td>
</tr>
<tr>
<td>bindValue()</td>
<td>将一个值绑定到对应的一个参数中</td>
</tr>
<tr>
<td>closeCursor()</td>
<td>关闭游标，使该声明再次被执行</td>
</tr>
<tr>
<td>columnCount()</td>
<td>在结果集中返回列的数目</td>
</tr>
<tr>
<td>errorCode()</td>
<td>获取错误码</td>
</tr>
<tr>
<td>errorInfo()</td>
<td>获取错误信息</td>
</tr>
<tr>
<td>execute()</td>
<td>执行一个预处理查询</td>
</tr>
<tr>
<td>fetch()</td>
<td>获取结果集的下一行，到结尾返回false</td>
</tr>
<tr>
<td>fetchAll()</td>
<td>获取结果集的所有行</td>
</tr>
<tr>
<td>fetchColumn()</td>
<td>获取某一列的下一个值</td>
</tr>
<tr>
<td>fetchObject()</td>
<td>获取结果集的下一行，作为对象返回</td>
</tr>
<tr>
<td>getAttribute()</td>
<td>获取属性</td>
</tr>
<tr>
<td>setAttribute()</td>
<td>设置属性</td>
</tr>
<tr>
<td>nextRowset()</td>
<td>获取下一行结果集</td>
</tr>
<tr>
<td>rowCount()</td>
<td>获取结果集的行数</td>
</tr>
<tr>
<td>getColumnMeta()</td>
<td>获取某一列的信息</td>
</tr>
<tr>
<td>setFetchMode()</td>
<td>设置获取结果集的类型</td>
</tr>
</tbody>
</table>
<h2 id="memcached">MemCached</h2>
<h3 id="memcached命令">MemCached命令</h3>
<blockquote>
<p>stats: 当前所有memcached服务器运行的状态信息<br>
add: 添加一个数据到服务器<br>
set: 替换一个已经存在的数据，如果数据不存在，则与add命令相同<br>
get: 从服务器端获取指定的数据<br>
delete: 删除指定的单个数据<br>
flush_all: 删除所有数据</p>
</blockquote>
<h3 id="在php中使用memcached">在PHP中使用MemCached</h3>
<p>需要安装memcached扩展包</p>
<pre><code class="language-php">Memcached::connect  // 打开一个到memcached的连接
Memcached::pconnect  // 打开一个到memcached的长连接
Memcached::addServer  // 分布式服务器添加一个服务器
Memcached::close  // 关闭一个memcached的连接
Memcached::getStats // 获取当前memcached服务器的状态
Memcached::add  // 添加一个值，若存在，返回false
Memcached::set  // 添加一个值，若存在，覆盖
Memcached::replace  // 替换一个值，类似于set                               
Memcached::get  // 获取一个数据                
Memcached::delete  // 删除一个数据
Memcached::flush   // 清空所有数据
</code></pre>
<h2 id="框架">框架</h2>
<p>一个框架需要的功能：</p>
<ul>
<li>目录组织结构</li>
<li>类加载</li>
<li>基础类</li>
<li>URL处理</li>
<li>输入处理</li>
<li>错误异常处理</li>
<li>扩展类</li>
</ul>
<h2 id="php安全和优化">PHP安全和优化</h2>
<ul>
<li>不信任用户输入、验证用户数据</li>
<li>及时修补漏洞</li>
<li>隐藏Apache和PHP（Apache的ServerSignature、ServerToken指令、PHP的expose_php()函数）</li>
<li>删除phpinfo()调用的所有实例</li>
<li>修改文档扩展名</li>
<li>拒绝访问某些类型的文件</li>
</ul>
<p>优化</p>
<ul>
<li>使用循环时，应该先计算长度，不要每次都计算一遍</li>
<li>使用<code>isset($str{10})</code>比<code>strlen($str) &gt; 10</code>更快，对于数组也一样</li>
<li><code>$i++</code>比<code>++$i</code>稍慢（仅适用PHP）</li>
</ul>

            </div>
            
            
              <div class="post-footer">
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong class="language" data-lan="author">本文作者：</strong>
      anhoder
    </li>
    <li class="post-copyright-link">
      <strong class="language" data-lan="link">本文链接：</strong>
      <a href="/post/wj0p65Bqw/" title="读《细说PHP》">/post/wj0p65Bqw/</a>
    </li>
    <li class="post-copyright-license">
      <strong class="language" data-lan="copyright">版权声明： </strong>
      本博客所有文章除特别声明外，均采用<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i> BY-NC-SA</a> 许可协议。转载请注明出处！
    </li>
  </ul>
  <div class="tags">
    
      <a href="/tag/wKIDH6M-M/"># PHP</a>
    
  </div>
  <div class="nav">
    <div class="nav-prev">
      
        <i class="fa fa-chevron-left"></i>
        <a class="nav-pc-next" title="PHP的Trait" href="/post/1q8juCKkk/">PHP的Trait</a class="nav-pc-next">
        <a class="nav-mobile-prev" title="PHP的Trait" href="/post/1q8juCKkk/">上一篇</a>
      
    </div>
    <div class="nav-next">
      
        <a class="nav-pc-next" title="读《高性能MySQL》---（三）" href="/post/sQNETQWN2/">读《高性能MySQL》---（三）</a>
        <a class="nav-mobile-next" title="读《高性能MySQL》---（三）" href="/post/sQNETQWN2/">下一篇</a>
        <i class="fa fa-chevron-right"></i>
      
    </div>
  </div>
</div>
            
            
  
    
      <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

<div id="gitalk-container"></div>

<script>
  var gitalk = new Gitalk({
    clientID: '8254f894b17fffeef6e2',
    clientSecret: 'aa345603999774a44649ad73ef7fe72ee45a021b',
    repo: 'personal-blog-comments',
    owner: 'anhoder',
    admin: ['anhoder'],
    id: (location.pathname).substring(0, 49),      // Ensure uniqueness and length less than 50
    distractionFreeMode: false  // Facebook-like distraction free mode
  })
  gitalk.render('gitalk-container')
</script>
    
    
  

          </div>
        </div>
      </div>
    </div>
    <div class="footer-box">
  <footer class="footer">
    <div class="poweredby">
      © Authored by <a href="https://github.com/anhoder">anhoder</a> since 2019.
    </div>
    <div class="copyright">
      Powered by <a href="https://github.com/getgridea/gridea" target="_blank">Gridea</a> | Theme By <a
        href="https://github.com/hsxyhao/gridea-theme-next" target="_blank">HsxyHao</a>
    </div>
  </footer>
  
  
  <div class="pisces back-to-top" id="back_to_top">
    <i class="fa fa-arrow-up"></i>
    
    <span class="scrollpercent">
      <span id="back_to_top_text">0</span>%
    </span>
    
  </div>
  
  
  
<link rel="stylesheet" href="/media/live2d/css/live2d.css" />
<div class="box-scale">
  <div id="landlord" style="left: 100%px;bottom: 100%px;"
    data-key="">
    <canvas id="live2d" width="500" height="560" class="live2d"></canvas>
    
  </div>
</div>
<div id="open_live2d">召唤看板娘</div>
<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
  var message_Path = 'https://cdn.jsdelivr.net/gh/anhoder/source-for-blog@master/';
  let landlord = document.querySelector('#landlord');
  var apiKey = landlord.dataset.key;
</script>
<script type="text/javascript" src="/media/live2d/js/live2d.js"></script>
<script>
	var home_Path = document.location.protocol + '//' + window.document.location.hostname + ":" + window.document.location.port + '/';
	var userAgent = window.navigator.userAgent.toLowerCase();
	var norunAI = ["android", "iphone", "ipod", "ipad", "windows phone", "mqqbrowser", "msie", "trident/7.0"];
	var norunFlag = false;

	for (var i = 0; i < norunAI.length; i++) {
		if (userAgent.indexOf(norunAI[i]) > -1) {
			norunFlag = true;
			break;
		}
	}

	if (!window.WebGLRenderingContext) {
		norunFlag = true;
	}

	if (!norunFlag) {
		var hitFlag = false;
		var AIFadeFlag = false;
		var liveTlakTimer = null;
		var sleepTimer_ = null;
		var AITalkFlag = false;
		var talkNum = 0;
		(function () {
			function renderTip(template, context) {
				var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
				return template.replace(tokenReg, function (word, slash1, token, slash2) {
					if (slash1 || slash2) {
						return word.replace('\\', '');
					}
					var variables = token.replace(/\s/g, '').split('.');
					var currentObject = context;
					var i, length, variable;
					for (i = 0, length = variables.length; i < length; ++i) {
						variable = variables[i];
						currentObject = currentObject[variable];
						if (currentObject === undefined || currentObject === null) return '';
					}
					return currentObject;
				});
			}

			String.prototype.renderTip = function (context) {
				return renderTip(this, context);
			};

			var re = /x/;
			re.toString = function () {
				showMessage('哈哈，你打开了控制台，是想要看看我的秘密吗？', 5000);
				return '';
			};

			$(document).on('copy', function () {
				showMessage('你都复制了些什么呀，转载要记得加上出处哦~~', 5000);
			});

			function initTips() {
				$.ajax({
					cache: true,
					url: message_Path + 'message.json',
					dataType: "json",
					success: function (result) {
						$.each(result.mouseover, function (index, tips) {
							$(tips.selector).mouseover(function () {
								var text = tips.text;
								if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
								text = text.renderTip({ text: $(this).text() });
								showMessage(text, 3000);
								talkValTimer();
								clearInterval(liveTlakTimer);
								liveTlakTimer = null;
							});
							$(tips.selector).mouseout(function () {
								showHitokoto();
								if (liveTlakTimer == null) {
									liveTlakTimer = window.setInterval(function () {
										showHitokoto();
									}, 15000);
								};
							});
						});
						$.each(result.click, function (index, tips) {
							$(tips.selector).click(function () {
								if (hitFlag) {
									return false
								}
								hitFlag = true;
								setTimeout(function () {
									hitFlag = false;
								}, 8000);
								var text = tips.text;
								if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
								text = text.renderTip({ text: $(this).text() });
								showMessage(text, 3000);
							});
							clearInterval(liveTlakTimer);
							liveTlakTimer = null;
							if (liveTlakTimer == null) {
								liveTlakTimer = window.setInterval(function () {
									showHitokoto();
								}, 15000);
							};
						});
					}
				});
			}
			initTips();

			var text;
			if (document.referrer !== '') {
				var referrer = document.createElement('a');
				referrer.href = document.referrer;
				text = '嗨！来自 <span style="color:#0099cc;">' + referrer.hostname + '</span> 的朋友！';
				var domain = referrer.hostname.split('.')[1];
				if (domain == 'baidu') {
					text = '嗨！ 来自 百度搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				} else if (domain == 'so') {
					text = '嗨！ 来自 360搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				} else if (domain == 'google') {
					text = '嗨！ 来自 谷歌搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				}
			} else {
				if (window.location.href == home_Path) { //主页URL判断，需要斜杠结尾
					var now = (new Date()).getHours();
					if (now > 23 || now <= 5) {
						text = '你是夜猫子呀？这么晚还不睡觉，明天起的来嘛？';
					} else if (now > 5 && now <= 7) {
						text = '早上好！一日之计在于晨，美好的一天就要开始了！';
					} else if (now > 7 && now <= 11) {
						text = '上午好！工作顺利嘛，不要久坐，多起来走动走动哦！';
					} else if (now > 11 && now <= 14) {
						text = '中午了，工作了一个上午，现在是午餐时间！';
					} else if (now > 14 && now <= 17) {
						text = '午后很容易犯困呢，今天的运动目标完成了吗？';
					} else if (now > 17 && now <= 19) {
						text = '傍晚了！窗外夕阳的景色很美丽呢，最美不过夕阳红~~';
					} else if (now > 19 && now <= 21) {
						text = '晚上好，今天过得怎么样？';
					} else if (now > 21 && now <= 23) {
						text = '已经这么晚了呀，早点休息吧，晚安~~';
					} else {
						text = '嗨~ 快来逗我玩吧！';
					}
				} else {
					text = '欢迎阅读<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				}
			}
			showMessage(text, 12000);
		})();

		liveTlakTimer = setInterval(function () {
			showHitokoto();
		}, 15000);

		function showHitokoto() {
			if (sessionStorage.getItem("Sleepy") !== "1") {
				if (!AITalkFlag) {
					$.getJSON('https://v1.hitokoto.cn/', function (result) {
						talkValTimer();
						showMessage(result.hitokoto, 0);
					});
				}
			} else {
				hideMessage(0);
				if (sleepTimer_ == null) {
					sleepTimer_ = setInterval(function () {
						checkSleep();
					}, 200);
				}
			}
		}

		function checkSleep() {
			var sleepStatu = sessionStorage.getItem("Sleepy");
			if (sleepStatu !== '1') {
				talkValTimer();
				showMessage('你回来啦~', 0);
				clearInterval(sleepTimer_);
				sleepTimer_ = null;
			}
		}

		function showMessage(text, timeout) {
			if (Array.isArray(text)) text = text[Math.floor(Math.random() * text.length + 1) - 1];
			$('.message').stop();
			$('.message').html(text);
			$('.message').fadeTo(200, 1);
			//if (timeout === null) timeout = 5000;
			//hideMessage(timeout);
		}
		function talkValTimer() {
			$('#live_talk').val('1');
		}

		function hideMessage(timeout) {
			//$('.message').stop().css('opacity',1);
			if (timeout === null) timeout = 5000;
			$('.message').delay(timeout).fadeTo(200, 0);
		}

		function initLive2d() {
			$('#hideButton').on('click', function () {
				if (AIFadeFlag) {
					return false;
				} else {
					AIFadeFlag = true;
					localStorage.setItem("live2dhidden", "0");
					$('#landlord').fadeOut(200);
					$('#open_live2d').delay(200).fadeIn(200);
					setTimeout(function () {
						AIFadeFlag = false;
					}, 300);
				}
			});
			$('#open_live2d').on('click', function () {
				if (AIFadeFlag) {
					return false;
				} else {
					AIFadeFlag = true;
					localStorage.setItem("live2dhidden", "1");
					$('#open_live2d').fadeOut(200);
					$('#landlord').delay(200).fadeIn(200);
					setTimeout(function () {
						AIFadeFlag = false;
					}, 300);
				}
			});
			$('#youduButton').on('click', function () {
				if ($('#youduButton').hasClass('doudong')) {
					var typeIs = $('#youduButton').attr('data-type');
					$('#youduButton').removeClass('doudong');
					$('body').removeClass(typeIs);
					$('#youduButton').attr('data-type', '');
				} else {
					var duType = $('#duType').val();
					var duArr = duType.split(",");
					var dataType = duArr[Math.floor(Math.random() * duArr.length)];

					$('#youduButton').addClass('doudong');
					$('#youduButton').attr('data-type', dataType);
					$('body').addClass(dataType);
				}
			});
			if (apiKey) {
				$('#showInfoBtn').on('click', function () {
					var live_statu = $('#live_statu_val').val();
					if (live_statu == "0") {
						return
					} else {
						$('#live_statu_val').val("0");
						$('.live_talk_input_body').fadeOut(500);
						AITalkFlag = false;
						showHitokoto();
						$('#showTalkBtn').show();
						$('#showInfoBtn').hide();
					}
				});
				$('#showTalkBtn').on('click', function () {
					var live_statu = $('#live_statu_val').val();
					if (live_statu == "1") {
						return
					} else {
						$('#live_statu_val').val("1");
						$('.live_talk_input_body').fadeIn(500);
						AITalkFlag = true;
						$('#showTalkBtn').hide();
						$('#showInfoBtn').show();

					}
				});
				$('#talk_send').on('click', function () {
					var info_ = $('#AIuserText').val();
					var userid_ = $('#AIuserName').val();
					if (info_ == "") {
						showMessage('写点什么吧！', 0);
						return;
					}
					if (userid_ == "") {
						showMessage('聊之前请告诉我你的名字吧！', 0);
						return;
					}
					showMessage('思考中~', 0);
					let protocol = window.location.protocol.indexOf("s") > 0 ? "https" : "http";
					$.ajax({
						type: "get",
						url: `${protocol}://www.tuling123.com/openapi/api?key=${apiKey}&info=${info_}`,
						dataType: "json",
						success: function (res) {
							talkValTimer();
							showMessage(res.text, 0);
							$('#AIuserText').val("");
							sessionStorage.setItem("live2duser", userid_);
						},
						error: function (e) {
							talkValTimer();
							showMessage('似乎有什么错误，请和站长联系！', 0);
						}
					});
				});
			} else {
				$('#showInfoBtn').hide();
				$('#showTalkBtn').hide();
			}
			//获取音乐信息初始化
			var bgmListInfo = $('input[name=live2dBGM]');
			if (bgmListInfo.length == 0) {
				$('#musicButton').hide();
			} else {
				var bgmPlayNow = parseInt($('#live2d_bgm').attr('data-bgm'));
				var bgmPlayTime = 0;
				var live2dBGM_Num = sessionStorage.getItem("live2dBGM_Num");
				var live2dBGM_PlayTime = sessionStorage.getItem("live2dBGM_PlayTime");
				if (live2dBGM_Num) {
					if (live2dBGM_Num <= $('input[name=live2dBGM]').length - 1) {
						bgmPlayNow = parseInt(live2dBGM_Num);
					}
				}
				if (live2dBGM_PlayTime) {
					bgmPlayTime = parseInt(live2dBGM_PlayTime);
				}
				var live2dBGMSrc = bgmListInfo.eq(bgmPlayNow).val();
				$('#live2d_bgm').attr('data-bgm', bgmPlayNow);
				$('#live2d_bgm').attr('src', live2dBGMSrc);
				$('#live2d_bgm')[0].currentTime = bgmPlayTime;
				$('#live2d_bgm')[0].volume = 0.5;
				var live2dBGM_IsPlay = sessionStorage.getItem("live2dBGM_IsPlay");
				var live2dBGM_WindowClose = sessionStorage.getItem("live2dBGM_WindowClose");
				if (live2dBGM_IsPlay == '0' && live2dBGM_WindowClose == '0') {
					$('#live2d_bgm')[0].play();
					$('#musicButton').addClass('play');
				}
				sessionStorage.setItem("live2dBGM_WindowClose", '1');
				$('#musicButton').on('click', function () {
					if ($('#musicButton').hasClass('play')) {
						$('#live2d_bgm')[0].pause();
						$('#musicButton').removeClass('play');
						sessionStorage.setItem("live2dBGM_IsPlay", '1');
					} else {
						$('#live2d_bgm')[0].play();
						$('#musicButton').addClass('play');
						sessionStorage.setItem("live2dBGM_IsPlay", '0');
					}
				});
				window.onbeforeunload = function () {
					sessionStorage.setItem("live2dBGM_WindowClose", '0');
					if ($('#musicButton').hasClass('play')) {
						sessionStorage.setItem("live2dBGM_IsPlay", '0');
					}
				}
				document.getElementById('live2d_bgm').addEventListener("timeupdate", function () {
					var live2dBgmPlayTimeNow = document.getElementById('live2d_bgm').currentTime;
					sessionStorage.setItem("live2dBGM_PlayTime", live2dBgmPlayTimeNow);
				});
				document.getElementById('live2d_bgm').addEventListener("ended", function () {
					var listNow = parseInt($('#live2d_bgm').attr('data-bgm'));
					listNow++;
					if (listNow > $('input[name=live2dBGM]').length - 1) {
						listNow = 0;
					}
					var listNewSrc = $('input[name=live2dBGM]').eq(listNow).val();
					sessionStorage.setItem("live2dBGM_Num", listNow);
					$('#live2d_bgm').attr('src', listNewSrc);
					$('#live2d_bgm')[0].play();
					$('#live2d_bgm').attr('data-bgm', listNow);
				});
				document.getElementById('live2d_bgm').addEventListener("error", function () {
					$('#live2d_bgm')[0].pause();
					$('#musicButton').removeClass('play');
					showMessage('音乐似乎加载不出来了呢！', 0);
				});
			}
			//获取用户名
			var live2dUser = sessionStorage.getItem("live2duser");
			if (live2dUser !== null) {
				$('#AIuserName').val(live2dUser);
			}
			//获取位置
			var landL = sessionStorage.getItem("historywidth");
			var landB = sessionStorage.getItem("historyheight");
			if (landL == null || landB == null) {
				landL = '5px'
				landB = '0px'
			}
			$('#landlord').css('left', landL + 'px');
			$('#landlord').css('bottom', landB + 'px');
			//移动
			function getEvent() {
				return window.event || arguments.callee.caller.arguments[0];
			}
			var smcc = document.getElementById("landlord");
			var moveX = 0;
			var moveY = 0;
			var moveBottom = 0;
			var moveLeft = 0;
			var moveable = false;
			var docMouseMoveEvent = document.onmousemove;
			var docMouseUpEvent = document.onmouseup;
			smcc.onmousedown = function () {
				var ent = getEvent();
				moveable = true;
				moveX = ent.clientX;
				moveY = ent.clientY;
				var obj = smcc;
				moveBottom = parseInt(obj.style.bottom);
				moveLeft = parseInt(obj.style.left);
				if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
					window.getSelection().removeAllRanges();
				}
				document.onmousemove = function () {
					if (moveable) {
						var ent = getEvent();
						var x = moveLeft + ent.clientX - moveX;
						var y = moveBottom + (moveY - ent.clientY);
						obj.style.left = x + "px";
						obj.style.bottom = y + "px";
					}
				};
				document.onmouseup = function () {
					if (moveable) {
						var historywidth = obj.style.left;
						var historyheight = obj.style.bottom;
						historywidth = historywidth.replace('px', '');
						historyheight = historyheight.replace('px', '');
						sessionStorage.setItem("historywidth", historywidth);
						sessionStorage.setItem("historyheight", historyheight);
						document.onmousemove = docMouseMoveEvent;
						document.onmouseup = docMouseUpEvent;
						moveable = false;
						moveX = 0;
						moveY = 0;
						moveBottom = 0;
						moveLeft = 0;
					}
				};
			};
		}
		$(document).ready(function () {
			var AIimgSrc = [];
			let chooseLive2d = 'plt'
			if (chooseLive2d === 'histoire') {
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_00.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_01.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_02.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_03.png");
			} else if (chooseLive2d === 'rem') {
				AIimgSrc.push(message_Path + "model/rem/remu2048/texture_00.png");
			} else if (chooseLive2d === 'aoba') {
				AIimgSrc.push(message_Path + "model/aoba/textures/texture_00.png");
			} else if (chooseLive2d === 'hijiki') {
				AIimgSrc.push(message_Path + "model/hijiki/moc/hijiki.2048/texture_00.png");
			} else if (chooseLive2d === 'tororo') {
				AIimgSrc.push(message_Path + "model/tororo/moc/tororo.2048/texture_00.png");
			} else if (chooseLive2d === 'plt') {
				AIimgSrc.push(message_Path + "model/plt/moc/plt.2048/texture_00.png");
			}
			var images = [];
			var imgLength = AIimgSrc.length;
			var loadingNum = 0;
			for (var i = 0; i < imgLength; i++) {
				images[i] = new Image();
				images[i].src = AIimgSrc[i];
				images[i].onload = function () {
					loadingNum++;
					if (loadingNum === imgLength) {
						var live2dhidden = localStorage.getItem("live2dhidden");
						if (live2dhidden === "0") {
							setTimeout(function () {
								$('#open_live2d').fadeIn(200);
							}, 1300);
						} else {
							setTimeout(function () {
								$('#landlord').fadeIn(200);
							}, 1300);
						}
						let model = '';
						if (chooseLive2d === 'histoire') {
							model = message_Path + "model/histoire/model.json";
						} else if (chooseLive2d === 'rem') {
							model = message_Path + "model/rem/model.json";
						} else if (chooseLive2d === 'aoba') {
							model = message_Path + "model/aoba/model.json";
						} else if (chooseLive2d === 'hijiki') {
							model = message_Path + "model/hijiki/hijiki.model.json";
						} else if (chooseLive2d === 'tororo') {
							model = message_Path + "model/tororo/tororo.model.json";
						} else if (chooseLive2d === 'plt') {
							model = message_Path + "model/plt/model.json?v=1617466520";
						}
						setTimeout(function () {
							loadlive2d("live2d", model);
						}, 1000);
						initLive2d();
						images = null;
					}
				}
			}
		});
	}
</script>
  
  
</div>
<script>

  let sideBarOpen = 'sidebar-open';
  let body = document.body;
  let back2Top = document.querySelector('#back_to_top'),
    back2TopText = document.querySelector('#back_to_top_text'),
    drawerBox = document.querySelector('#drawer_box'),
    rightSideBar = document.querySelector('.sidebar'),
    viewport = document.querySelector('body');

  function scrollAnimation(currentY, targetY) {

    let needScrollTop = targetY - currentY
    let _currentY = currentY
    setTimeout(() => {
      const dist = Math.ceil(needScrollTop / 10)
      _currentY += dist
      window.scrollTo(_currentY, currentY)
      if (needScrollTop > 10 || needScrollTop < -10) {
        scrollAnimation(_currentY, targetY)
      } else {
        window.scrollTo(_currentY, targetY)
      }
    }, 1)
  }

  back2Top.addEventListener("click", function (e) {
    scrollAnimation(document.scrollingElement.scrollTop, 0);
    e.stopPropagation();
    return false;
  });

  window.addEventListener('scroll', function (e) {
    let percent = document.scrollingElement.scrollTop / (document.scrollingElement.scrollHeight - document.scrollingElement.clientHeight) * 100;
    if (percent > 1 && !back2Top.classList.contains('back-top-active')) {
      back2Top.classList.add('back-top-active');
    }
    if (percent == 0) {
      back2Top.classList.remove('back-top-active');
    }
    if (back2TopText) {
      back2TopText.textContent = Math.floor(percent);
    }
  });


  let hasCacu = false;
  window.onresize = function () {
    calcuHeight();
  }

  function calcuHeight() {
    // 动态调整站点概览高度
    if (!hasCacu && back2Top.classList.contains('pisces') || back2Top.classList.contains('gemini')) {
      let sideBar = document.querySelector('.sidebar');
      let navUl = document.querySelector('#site_nav');
      sideBar.style = 'margin-top:' + (navUl.offsetHeight + navUl.offsetTop + 15) + 'px;';
      hasCacu = true;
    }
  }
  calcuHeight();

  let open = false, MOTION_TIME = 300, RIGHT_MOVE_DIS = '320px';

  if (drawerBox) {
    let rightMotions = document.querySelectorAll('.right-motion');
    let right = drawerBox.classList.contains('right');

    let transitionDir = right ? "transition.slideRightIn" : "transition.slideLeftIn";

    let openProp, closeProp;
    if (right) {
      openProp = {
        paddingRight: RIGHT_MOVE_DIS
      };
      closeProp = {
        paddingRight: '0px'
      };
    } else {
      openProp = {
        paddingLeft: RIGHT_MOVE_DIS
      };
      closeProp = {
        paddingLeft: '0px'
      };
    }

    drawerBox.onclick = function () {
      open = !open;
      window.Velocity(rightSideBar, 'stop');
      window.Velocity(viewport, 'stop');
      window.Velocity(rightMotions, 'stop');
      if (open) {
        window.Velocity(rightSideBar, {
          width: RIGHT_MOVE_DIS
        }, {
          duration: MOTION_TIME,
          begin: function () {
            window.Velocity(rightMotions, transitionDir, {});
          }
        })
        window.Velocity(viewport, openProp, {
          duration: MOTION_TIME
        });
      } else {
        window.Velocity(rightSideBar, {
          width: '0px'
        }, {
          duration: MOTION_TIME,
          begin: function () {
            window.Velocity(rightMotions, {
              opacity: 0
            });
          }
        })
        window.Velocity(viewport, closeProp, {
          duration: MOTION_TIME
        });
      }
      for (let i = 0; i < drawerBox.children.length; i++) {
        drawerBox.children[i].classList.toggle('muse-line');
      }
      drawerBox.classList.toggle(sideBarOpen);
    }
  }

  // 链接跳转
  let newWindow = 'false'
  if (newWindow === 'true') {
    let links = document.querySelectorAll('.post-body a')
    links.forEach(item => {
      if (!item.classList.contains('btn')) {
        item.setAttribute("target", "_blank");
      }
    })
  }

  let faSearch = document.querySelector('#fa_search');
  faSearch && faSearch.addEventListener('click', function () {
    document.querySelector('#search_mask').style = ''
  })

  // 代码高亮
  hljs.initHighlightingOnLoad();
  
  // 离开当前页title变化
  var leaveTitle = "";
  if (leaveTitle) {
    document.addEventListener('visibilitychange', function () {
      if (document.visibilityState == 'hidden') {
        normal_title = document.title;
        document.title = leaveTitle;
      } else {
        document.title = normal_title;
      }
    });
  }

</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>

<script>
  let images = document.querySelectorAll('.section img');
  console.log(images);
  images.forEach(image => {
    if (image.classList.contains('no-fancybox')) {
      return;
    }

    var parent = image.parentElement;
    var next = image.nextElementSibling;
    parent.removeChild(image);
    var aelem = document.createElement('a');
    aelem.href = image.src;
    aelem.dataset['fancybox'] = 'images';
    aelem.dataset['rel'] = 'fancybox-button';
    aelem.classList.add('fancybox');
    aelem.appendChild(image);
    parent.insertBefore(aelem, next);
  })
</script>
    <div class="reward-mask" style="display: none;">
  <div class="reward-relative">
    <span class="close" aria-hidden="true">x</span>
    <div class="reward-body">
      <h2>感谢您的支持，我会继续努力的!</h2>
      <div class="reward-img-box">
        <div style="position: relative; width: 140px; height: 140px;">
          
          
          
        </div>
      </div>
      <p class="reward-word">扫码打赏，你说多少就多少</p>
      <p class="reward-tip">打开微信扫一扫，即可进行扫码打赏哦</p>
    </div>
    <div class="bottom">
      
      
    </div>
  </div>
</div>
<style>
  .reward-mask {
    position: fixed;
    z-index: 99999;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #00000054;
  }

  .reward-relative {
    position: relative;
    width: 480px;
    text-align: center;
    margin: 0 auto;
    border-radius: 5px;
    background-color: #fff;
    top: 50%;
    margin-top: -205px;
  }

  .reward-relative .close {
    position: absolute;
    right: 10px;
    font-weight: normal;
    font-size: 16px;
    color: #929292;
  }

  .reward-body {
    padding: 40px 20px 20px;
  }

  .bottom {
    display: flex;
  }

  .reward-btn {
    text-align: center;
  }

  .reward-btn-text {
    display: inline-block;
    cursor: pointer;
    width: 60px;
    height: 60px;
    line-height: 60px;
    border-radius: 50%;
    background-color: #ff9734;
    color: #FFF;
    margin-top: 20px;
  }

  .pay-text {
    margin-top: 10px;
    padding: 10px;
    flex: 1;
    transition: all .2s linear;
  }

  .pay-text:hover {
    background-color: #a5a5a536;
  }

  .reward-body h2 {
    padding-top: 10px;
    text-align: center;
    color: #a3a3a3;
    font-size: 16px;
    font-weight: normal;
    margin: 0 0 20px;
  }

  .reward-body h2:after,
  .reward-body h2:before {
    font-family: Arial, Helvetica, sans-serif;
    background: 0 0;
    width: 0;
    height: 0;
    font-style: normal;
    color: #eee;
    font-size: 80px;
    position: absolute;
    top: 20px;
  }

  .reward-body h2:before {
    content: '\201c';
    left: 50px;
  }

  .reward-body h2:after {
    content: '\201d';
    right: 80px;
  }

  .reward-img-box {
    display: inline-block;
    padding: 10px;
    border: 6px solid #ea5f00;
    margin: 0 auto;
    border-radius: 3px;
    position: relative;
  }

  .reward-img {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
  }

  @media (max-width: 767px) {
    .reward-relative {
      height: 100%;
      top: 0px;
      margin-top: 0;
      width: auto;
    }

    .reward-relative .bottom {
      flex-direction: column;
    }

    .reward-relative .pay-text {
      width: 80%;
      margin: 5px auto;
      border: 1px solid silver;
      padding: 6px;
      border-radius: 4px;
    }

    .reward-body h2:after {
      right: 40px;
    }

    .reward-body h2:after,
    .reward-body h2:before {
      font-size: 60px;
    }

    .reward-body h2:before {
      left: 20px;
    }
  }
</style>
<script>
  !function () {
    var mask = document.querySelector('.reward-mask');
    let close = document.querySelector('.reward-relative .close');
    let rewardBtn = document.querySelector('.reward-btn');

    let zfb = document.querySelector('#zfb'),
      wx = document.querySelector('#wx'),
      zfbBtn = document.querySelector('#zfbBtn'),
      wxBtn = document.querySelector('#wxBtn');

    if (zfbBtn && wxBtn) {
      zfbBtn.addEventListener('click', () => {
        window.Velocity(zfb, 'transition.slideLeftIn', {
          duration: 400
        });
        window.Velocity(wx, 'transition.slideRightOut', {
          display: 'none',
          duration: 400
        });
      });

      wxBtn.addEventListener('click', () => {
        window.Velocity(wx, 'transition.slideRightIn', {
          duration: 400
        });
        window.Velocity(zfb, 'transition.slideLeftOut', {
          display: 'none',
          duration: 400
        });
      });
    }

    rewardBtn && rewardBtn.addEventListener('click', (e) => {
      window.Velocity(mask, 'transition.slideDownIn', {
        duration: 400
      })
    });

    close.addEventListener('click', (e) => {
      e.preventDefault();
      window.Velocity(mask, 'transition.slideUpOut', {
        duration: 400
      })
    })
  }()
</script>

  </div>
</body>

<input hidden id="copy" />
<script>
  !function () {
    let times = document.querySelectorAll('.publish-time');
    for (let i = 0; i < times.length; i++) {
      let date = times[i].dataset.t;
      let time = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000);
      if (time < 60) {
        str = time + '秒之前';
      } else if (time < 3600) {
        str = Math.floor(time / 60) + '分钟之前';
      } else if (time >= 3600 && time < 86400) {
        str = Math.floor(time / 3600) + '小时之前';
      } else if (time >= 86400 && time < 259200) {
        str = Math.floor(time / 86400) + '天之前';
      } else {
        str = times[i].textContent;
      }
      times[i].textContent = str;
    }
  }();
</script>

<script>
  let language = '';
  if (language !== '') {
    let map = new Map();
    if (language === 'en') {
      map.set('search', 'Search');
      map.set('category', 'Categories');
      map.set('article', 'Articles');
      map.set('tag', 'Tags');
      map.set('top', 'Top');
      map.set('publish', 'published');
      map.set('minute', ' minutes');
      map.set('read-more', 'Read More');
      map.set('view', 'View');
      map.set('words', ' words');
      map.set('category-in', 'category in');
      map.set('preview', 'Meta');
      map.set('index', 'Toc');
      map.set('no-archives', "You haven't created yet");
      map.set('archives', " articles in total");
      map.set('cloud-tags', " tags in total");
      map.set('copyright', "Copyright: ");
      map.set('author', "Author: ");
      map.set('link', "Link: ");
      map.set('leave-message', "Leave a message");
      map.set('format', "Links Format");
      map.set('site-name', "Name: ");
      map.set('site-link', "Link: ");
      map.set('site-desc', "Desc: ");
      map.set('stat', " related results, taking ");
      map.set('stat-time', " ms");
      map.set('site-img', "Image: ");
    }

    if (map.size > 0) {
      let lanElems = document.querySelectorAll('.language');
      lanElems.forEach(elem => {
        let lan = elem.dataset.lan, text = map.get(lan);
        if (elem.__proto__ === HTMLInputElement.prototype) {
          elem.placeholder = text
        } else {
          if (elem.dataset.count) {
            text = elem.dataset.count + text;
          }
          elem.textContent = text;
        }
      })
    }
  }
  //拿来主义(真香)^_^，Clipboard 实现摘自掘金 https://juejin.im/post/5aefeb6e6fb9a07aa43c20af
  window.Clipboard = (function (window, document, navigator) {
    var textArea,
      copy;

    // 判断是不是ios端
    function isOS() {
      return navigator.userAgent.match(/ipad|iphone/i);
    }
    //创建文本元素
    function createTextArea(text) {
      textArea = document.createElement('textArea');
      textArea.value = text;
      textArea.style.width = 0;
      textArea.style.height = 0;
      textArea.clientHeight = 0;
      textArea.clientWidth = 0;
      document.body.appendChild(textArea);
    }
    //选择内容
    function selectText() {
      var range,
        selection;

      if (isOS()) {
        range = document.createRange();
        range.selectNodeContents(textArea);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textArea.setSelectionRange(0, 999999);
      } else {
        textArea.select();
      }
    }

    //复制到剪贴板
    function copyToClipboard() {
      try {
        document.execCommand("Copy")
      } catch (err) {
        alert("复制错误！请手动复制！")
      }
      document.body.removeChild(textArea);
    }

    copy = function (text) {
      createTextArea(text);
      selectText();
      copyToClipboard();
    };

    return {
      copy: copy
    };
  })(window, document, navigator);

  function copyCode(e) {
    if (e.srcElement.tagName === 'SPAN' && e.srcElement.classList.contains('copy-code')) {
      let code = e.currentTarget.querySelector('code');
      var text = code.innerText;
      if (e.srcElement.textContent === '复制成功') {
        return;
      }
      e.srcElement.textContent = '复制成功';
      (function (elem) {
        setTimeout(() => {
          if (elem.textContent === '复制成功') {
            elem.textContent = '复制代码'
          }
        }, 1000);
      })(e.srcElement)
      Clipboard.copy(text);
    }
  }

  let pres = document.querySelectorAll('pre');
  pres.forEach(pre => {
    let code = pre.querySelector('code');
    let copyElem = document.createElement('span');
    copyElem.classList.add('copy-code');
    copyElem.textContent = '复制代码';
    pre.appendChild(copyElem);
    pre.onclick = copyCode
  })

</script>
<script src="/media/js/motion.js"></script>


<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>
<script>
  var scroll = new SmoothScroll('a[href*="#"]', {
    speed: 200
  });
</script>



<script src="/media/js/cool.js"></script>



</html>